package org.mx.dal.hibernate.single.service;

import org.mx.dal.hibernate.single.entity.AccountEntity;
import org.mx.dal.hibernate.single.entity.RoleEntity;
import org.mx.dal.service.GeneralDictAccessor;
import org.mx.error.UserInterfaceSystemErrorException;
import org.mx.error.UserInterfaceSystemErrorException.SystemErrors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@SuppressWarnings("javadoc")
@Component
public class TransactionService {
	@Autowired
	@Qualifier("generalDictAccessor")
	private GeneralDictAccessor accessor;

	@Transactional
	public void clean() {
		accessor.clear(AccountEntity.class);
		accessor.clear(RoleEntity.class);
	}

	@Transactional
	public void normalTransaction() {
		for (int index = 1; index < 10; index++) {
			AccountEntity a = new AccountEntity();
			a.setId("id " + index);
			a.setCode("code " + index);
			a.setName("name " + index);
			a.setDesc("desc " + index);
			accessor.save(a);
		}
		RoleEntity role = new RoleEntity();
		role.setId("commit");
		role.setCode("commit");
		role.setName("commit");
		role.setDesc("commit");
		accessor.save(role);
	}

	@Transactional
	public void rollbackTransaction() {
		AccountEntity a = new AccountEntity();
		a.setId("17");
		a.setCode("code 17");
		a.setName("name 17");
		a.setDesc("desc 17");
		accessor.save(a);
		RoleEntity role = new RoleEntity();
		role.setId("rollback");
		role.setCode("rollback");
		role.setName("rollback");
		role.setDesc("rollback");
		accessor.save(role);
		throw new UserInterfaceSystemErrorException(SystemErrors.SYSTEM_ILLEGAL_PARAM);
	}
}
